/**
 * Copyright (C) 2004-2009 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.onlyxiahui.of.muc.iq;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

import com.onlyxiahui.of.muc.bean.AffiliationInfo;
import com.onlyxiahui.of.muc.bean.MemberInfo;
import com.onlyxiahui.of.muc.bean.RoomMember;
import com.onlyxiahui.of.muc.dao.RoomDAO;

public class IQRoomMemberHandler extends IQHandler {

	private IQHandlerInfo info;
	private String serverName;

	private static final String MODULE_NAME = "Room Members Handler";
	private static final String NAME_SPACE = "http://www.jivesoftware.org/protocol/room#members";
	private static final String NAME_KEY = "members";

	public IQRoomMemberHandler() {
		super(MODULE_NAME);
		info = new IQHandlerInfo(NAME_KEY, NAME_SPACE);
	}

	@Override
	public IQ handleIQ(IQ packet) throws UnauthorizedException {
		IQ result = IQ.createResultIQ(packet);
		// String username = packet.getFrom().toBareJID();// .getNode();
		// JID jd = packet.getFrom();
		// JID toJid =packet.getTo();

		String roomName = null;
		Element pe = packet.getElement();
		Element ms = pe.element("members");
		if (null != ms) {
			Element m = ms.element("room");
			if (null != m) {
				roomName = m.getText();
			}
		}

		if (!serverName.equals(packet.getFrom().getDomain()) || roomName == null || roomName.isEmpty()) {
			result.setChildElement(packet.getChildElement().createCopy());
			result.setError(PacketError.Condition.not_allowed);
			return result;
		}

		List<AffiliationInfo> alist = RoomDAO.getAffiliationList(roomName);
		List<MemberInfo> mlist = RoomDAO.getMemberInfoList(roomName);

		Map<String, RoomMember> map = new HashMap<String, RoomMember>();

		for (AffiliationInfo ai : alist) {
			String jid = ai.getJid();
			int a = ai.getAffiliation();

			String role = "";

			switch (a) {
			case 10:
				role = "owner";
				break;
			case 20:
				role = "admin";
				break;
			case 30:
				role = "member";
				break;
			case 40:
				role = "outcast";
				break;
			case 50:
				role = "outcast";
				break;
			default:
				role = "member";
				break;
			}
			RoomMember rm = new RoomMember();
			rm.setJid(jid);
			rm.setNickname(jid);
			rm.setRole(role);

			map.put(jid, rm);
		}

		for (MemberInfo mi : mlist) {
			String jid = mi.getJid();
			String nickname = mi.getNickname();
			
			nickname = (null == nickname || nickname.isEmpty()) ? jid : nickname;
			
			RoomMember rm = map.get(jid);
			if (null == rm) {
				rm = new RoomMember();
				map.put(jid, rm);
			}
			String role = (null == rm.getRole() || rm.getRole().isEmpty()) ? "member" : rm.getRole();
			rm.setJid(jid);
			rm.setNickname(nickname);
			rm.setRole(role);
		}
		Element members = result.setChildElement(NAME_KEY, NAME_SPACE);
		for (RoomMember mi : map.values()) {
			Element member = members.addElement("member");
			member.addAttribute("jid", mi.getJid());
			member.addAttribute("nickname", mi.getNickname());
			member.addAttribute("role", mi.getRole());
			// member.addElement("jid").setText(mi.getJid());
			// member.addElement("nickname").setText(mi.getNickname());
			// member.addElement("role").setText(mi.getRole());
		}
		return result;
	}

	@Override
	public IQHandlerInfo getInfo() {
		return info;
	}

	@Override
	public void initialize(XMPPServer server) {
		super.initialize(server);
		serverName = server.getServerInfo().getXMPPDomain();
	}
}
